package tests;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import security.LoginService;
import services.ReunionService;
import utilities.PopulateDatabase;

@ContextConfiguration(locations = { "classpath:spring/datasource.xml",
"classpath:spring/config/packages.xml" })
@RunWith(SpringJUnit4ClassRunner.class)
public class CU51UnirseAReunionUnVecino {
	@Autowired
	private ReunionService reunionService;

	
	@Autowired
	private LoginService loginService;
	
	public void authenticate(String username) {
		UserDetails userDetails;
		TestingAuthenticationToken authenticationToken;
		SecurityContext context;
		userDetails = loginService.loadUserByUsername(username);
		authenticationToken = new TestingAuthenticationToken(userDetails, null);
		context = SecurityContextHolder.getContext();
		context.setAuthentication(authenticationToken);
	}
	
	@Before
	public void setUp() {
		PopulateDatabase.main(null);
	}
	
	@Test
	public void unirseAReunionVecinoTest(){
		authenticate("12345678K");
		
		reunionService.join(24);//Se une a una reunion con fecha futura
	}
	
	@Test(expected = IllegalArgumentException.class)
	public void unirseAReunionPasadaVecinoTest(){
		authenticate("12345678K");
		
		reunionService.join(23);//Se une a una reunion con fecha pasada
	}
	
	@Test(expected = IllegalArgumentException.class)
	public void unirseAReunionAdminTest(){
		authenticate("admin1");
		
		reunionService.join(24);//Se une a una reunion un administrador
	}
	
	@Test(expected = IllegalArgumentException.class)
	public void unirseAReunionVecinoAsistenteTest(){
		authenticate("12345678K");
		reunionService.join(24);
		reunionService.join(24);//Se une a una reunion ya unido
	}
	

	
	
}
